<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>七牛云文件上传测试</title>
</head>

<body>
    <h2>文件上传测试</h2>

    <!-- 文件选择 -->
    <input type="file" id="fileInput" />

    <!-- 单选按钮，选择上传目录 -->
    <label><input type="radio" name="directory" value="img" checked> 图片</label>
    <label><input type="radio" name="directory" value="file"> 文件</label>

    <!-- 上传按钮 -->
    <button onclick="uploadFile()">上传文件</button>

    <script>
        async function getUploadToken(directory) {
            return "0cJvcIno9goKc6ZtTVAehjTiAzH2Mp1mR2EjvSM6:uM1bGXswN5I6-OK-MRjXkzPXN-w=:eyJzY29wZSI6InNtb2ctaW5jb21lLWV4cG5lc2UiLCJkZWFkbGluZSI6MTc0MTg3MzEyMn0=";
            /*
            const response = await fetch(`/qiniu/token?directory=${directory}`, {
                headers: {
                    Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjQsIm5pY2tOYW1lIjoiMjIyIiwiaWF0IjoxNzQxNjk2NTQwLCJleHAiOjE3NDIzMDEzNDB9.9Pw9qtTbRgQ9DCVuqIn6ZZgg85Tf8dlzdgGJ6xn3uNo"
                }
            });
            const { uploadToken } = await response.json();
            return uploadToken;
            */
        }

        async function uploadFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            if (!file) {
                alert('请选择要上传的文件');
                return;
            }

            // 获取用户选择的目录
            const selectedDirectory = document.querySelector('input[name="directory"]:checked').value;

            // 获取上传凭证
            const uploadToken = await getUploadToken(selectedDirectory);
            if (!uploadToken) {
                alert('无法获取上传凭证');
                return;
            }

            // 准备表单数据
            const formData = new FormData();
            formData.append('file', file);
            formData.append('token', uploadToken);

            // 上传文件到七牛云
            const uploadResponse = await fetch('https://up-z2.qiniup.com/', {
                method: 'POST',
                body: formData,
                headers: {
                    Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjQsIm5pY2tOYW1lIjoiMjIyIiwiaWF0IjoxNzQxNjk2NTQwLCJleHAiOjE3NDIzMDEzNDB9.9Pw9qtTbRgQ9DCVuqIn6ZZgg85Tf8dlzdgGJ6xn3uNo"
                }
            });

            const data = await uploadResponse.json();

            if (data.key) {
                const fileUrl = `http://smog-income-expense/${data.key}`; // 替换为你的bucket域名
                console.log('文件上传成功:', fileUrl);

                // 将文件URL发送给服务端
                await notifyServer(fileUrl);
            } else {
                console.error('文件上传失败:', data);
            }
        }

        async function notifyServer(fileUrl) {
            const response = await fetch('/qiniu/saveUploadedUrl', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjQsIm5pY2tOYW1lIjoiMjIyIiwiaWF0IjoxNzQxNjk2NTQwLCJleHAiOjE3NDIzMDEzNDB9.9Pw9qtTbRgQ9DCVuqIn6ZZgg85Tf8dlzdgGJ6xn3uNo"

                },
                body: JSON.stringify({ url: fileUrl })
            });

            if (response.ok) {
                console.log('通知服务器成功');
            } else {
                console.error('通知服务器失败');
            }
        }
    </script>

</body>

</html>